﻿using System;
using System.IO;

namespace CoffeeScriptHandler
{
    public class TempScriptWriter
    {
        public string Write(string script)
        {
            var filename = Guid.NewGuid().ToString() + ".js";
            var tempContents = GetCoffee() + Environment.NewLine;
            tempContents += "var coffee_to_compile = \"\\" + Environment.NewLine;
            tempContents += script.Replace("\r\n", "\\n\\" + Environment.NewLine);
            tempContents += "\";" + Environment.NewLine + Environment.NewLine;
            tempContents += "WScript.Echo(CoffeeScript.compile(coffee_to_compile, {no_wrap: true} ));";
            using (var writer = new StreamWriter(filename))
            {
                writer.Write(tempContents);
            }
            return filename;
        }

        public static string GetCoffee()
        {
            return ReadFileFromAssembly("coffee-script.js");
        }

        private static string ReadFileFromAssembly(string filename)
        {
            string text;
            using (Stream s = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("CoffeeScriptHandler.Scripts." + filename))
            {
                using (var sr = new StreamReader(s))
                {
                    text = sr.ReadToEnd();
                }
            }
            return text;
        }
    }
}